package com.estore.service;

import com.estore.model.Product;

import java.io.*;
import java.util.*;

/**
 * 商品服务类，负责商品相关的业务逻辑
 * 目前使用内存Map模拟数据库
 */
public class ProductService {
    private final Map<String, Product> productData = new HashMap();
    private String dataFilePath;

    public ProductService() {

        this.initDefauitData();
        this.loadData();
    }

    private void initDefauitData() {
        Set<String> tagsForJavaBook = new HashSet();
        tagsForJavaBook.add("编程");
        tagsForJavaBook.add("畅销");
        tagsForJavaBook.add("热门");
        tagsForJavaBook.add("热门");
        Set<String> tagsForMySQLBook = new HashSet();
        tagsForMySQLBook.add("数据库");
        Set<String> tagsForHealthBook = new HashSet();
        tagsForHealthBook.add("健康");
        tagsForHealthBook.add("生活");
        this.productData.put("p001", new Product("p001", "Java从入门到精通", (double)99.0F, 100, tagsForJavaBook));
        this.productData.put("p002", new Product("p002", "高性能MySQL", (double)128.5F, 50, tagsForMySQLBook));
        this.productData.put("p003", new Product("p003", "颈椎康复指南", (double)45.0F, 200, tagsForHealthBook));
        this.productData.put("p004", new Product("p004", "生发秘籍", (double)88.0F, 0, tagsForHealthBook));

    }
    private void loadConfig() {
        Properties  properties= new Properties();
        try (InputStream inputStream=new FileInputStream("config.properties")){
            properties.load(inputStream);
            dataFilePath=properties.getProperty("data.file.path");
        }catch (IOException e){
            e.printStackTrace();
            dataFilePath="products.dat";
        }
    }
    public void saveData() {
        loadConfig();
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(dataFilePath))) {
            oos.writeObject(productData);
            System.out.println("商品数据保存成功！");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("保存数据失败：" + e.getMessage());
        }
    }

    public void loadData() {
        loadConfig();

        // 添加空值检查
        if (dataFilePath == null) {
            System.out.println("数据文件路径未设置，使用默认初始化数据。");
            return;
        }

        File file = new File(dataFilePath);
        if (!file.exists()) {
            System.out.println("数据文件不存在，使用默认初始化数据。");
            return;
        }

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(dataFilePath))) {
            Map<String, Product> loadedData = (Map<String, Product>) ois.readObject();
            productData.clear();
            productData.putAll(loadedData);
            System.out.println("商品数据加载成功！");
        } catch (FileNotFoundException e) {
            System.out.println("数据文件不存在，使用默认初始化数据。");
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("加载数据失败：" + e.getMessage());
        }
    }

    public void backupData() {
        loadConfig();
        File source = new File(dataFilePath);
        File target = new File(dataFilePath + ".bak");
        if (!source.exists()) {
            System.out.println("源数据文件不存在，无法备份！");
            return;
        }
        try (FileInputStream fis = new FileInputStream(source);
             FileOutputStream fos = new FileOutputStream(target)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            System.out.println("数据文件备份成功，备份文件：" + target.getName());
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("备份数据失败：" + e.getMessage());
        }
    }

    public List<Product> getAllProducts() {
        return new ArrayList(this.productData.values());
    }

    public Product findProductById(String id) {
        return (Product)this.productData.get(id);
    }
}